package linked;

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache1 {

    private final int capacity;

    private final Map<Integer, Integer> cache = new LinkedHashMap<>();

    public LRUCache1(int capacity) {
        this.capacity = capacity;
    }

    /**
     * 拿的时候就要翻新（先删后加）
     */
    public int get(int key) {
        Integer value = cache.remove(key);
        if (value != null) {
            cache.put(key, value);
            return value;
        }
        return -1;
    }

    /**
     * 加的时候：存在要翻新，不存在要判断是否满了
     */
    public void put(int key, int value) {
        if (cache.remove(key) != null) {
            cache.put(key, value);
            return;
        }
        if (cache.size() == capacity) {
            Integer eldestKey = cache.keySet().iterator().next();
            cache.remove(eldestKey);
        }
        cache.put(key, value);
    }
}
